<script setup>
import { onMounted, ref } from 'vue'
import { QueryPageentryApi, addApi, updateApi, deleteApi } from '@/api/warehousing_Entry'
import { ElMessage, ElMessageBox } from 'element-plus'

// 表单数据
const form = ref({
  batchNumber: '',
  status: ''
})

const disForm = ref({
  totalCount: '',
  batchNumber: '',
  predictedArrivalTime: '',
  consignorId: ''
})

const tableData = ref([])
const page = ref(1)
const pageSize = ref(10)
const total = ref(0)
const dialogVisible = ref(false)
const isEdit = ref(false)
const editId = ref(null)

// 重置表单
const resetForm = () => {
  disForm.value = {
    batchNumber: '',
    predictedArrivalTime: '',
    consignorId: '',
    totalCount: ''
  }
}

const handleClose = () => {
  dialogVisible.value = false
  resetForm()
  isEdit.value = false
  editId.value = null
}

const search = async () => {
  const result = await QueryPageentryApi(page.value, pageSize.value, form.value.batchNumber, form.value.status)
  total.value = result.total
  tableData.value = result.list
}

const remove = async (row) => {
  try {
    // 添加确认对话框
    await ElMessageBox.confirm('确定要删除这条记录吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    let res = await deleteApi(row.id)
    if (res.code) {
      ElMessage.success("删除成功")
      search()
    } else {
      ElMessage.error(res.message || "删除失败")
    }
  } catch (error) {
    // 用户取消删除
    ElMessage.info('已取消删除')
  }
}

const add = async () => {
  dialogVisible.value = true
  isEdit.value = false
  resetForm()
}

// 格式化日期的函数
const formatDate = (date) => {
  if (!date) return null
  const d = new Date(date)
  const year = d.getFullYear()
  const month = String(d.getMonth() + 1).padStart(2, '0')
  const day = String(d.getDate()).padStart(2, '0')
  const hours = String(d.getHours()).padStart(2, '0')
  const minutes = String(d.getMinutes()).padStart(2, '0')
  const seconds = String(d.getSeconds()).padStart(2, '0')
  
  return `${year}-${month}-${day}T${hours}:${minutes}:${seconds}`
}

const save = async () => {
  let result
  // 创建一个新的对象用于提交，处理日期格式
  const submitForm = {
    ...disForm.value,
    predictedArrivalTime: formatDate(disForm.value.predictedArrivalTime)
  }
  
  if (isEdit.value) {
    // 修改操作
    result = await updateApi(editId.value, submitForm)
  } else {
    // 新增操作
    result = await addApi(submitForm)
  }
  if (result.code) {
    ElMessage.success(isEdit.value ? "修改成功" : "新增成功")
    dialogVisible.value = false
    resetForm()
    search()
  } else {
    ElMessage.error(result.message || "操作失败")
  }
}

const handleCurrentChange = (val) => {
  page.value = val
  search()
}

const handleSizeChange = (val) => {
  pageSize.value = val
  search()
}

const handleClick = (row) => {
  isEdit.value = true
  editId.value = row.id
  // 填充表单数据
  disForm.value = {
    batchNumber: row.batchNumber,
    predictedArrivalTime: row.predictedArrivalTime ? new Date(row.predictedArrivalTime) : '',
    consignorId: row.consignorId,
    totalCount: row.totalCount
  }
  dialogVisible.value = true
}

onMounted(() => {
  search()
})
</script>

<template>
  <!--查询表单-->
  <el-form :model="form" :inline="true" label-width="auto" style="max-width: 1000px">
    <el-form-item>
      <el-input v-model="form.batchNumber" placeholder="批次号" />
    </el-form-item>

    <el-form-item>
      <el-select v-model="form.status" placeholder="状态" clearable>
        <el-option label="未确定" :value="0" />
        <el-option label="部分已确定" :value="1" />
        <el-option label="全部确认" :value="2" />
        <el-option label="拣货中" :value="3" />
        <el-option label="已上货" :value="4" />
      </el-select>
    </el-form-item>
    <el-button type="primary" @click="search()">查询</el-button>
    <el-button type="primary" @click="add">增加</el-button>
  </el-form>

  <!--表格数据-->
  <el-table :data="tableData" border style="width:1000px">
    <el-table-column prop="batchNumber" label="批次号" width="180" />
    <el-table-column prop="totalCount" label="到达总数" width="180" />
    <el-table-column prop="predictedArrivalTime" label="预计到达时间" />
    <el-table-column prop="consignorId" label="货主Id" />
    <el-table-column prop="status" label="状态" width="180">
      <template #default="scope">
        <el-tag v-if="scope.row.status === 0" type="info">未确定</el-tag>
        <el-tag v-else-if="scope.row.status === 1" type="warning">部分已确定</el-tag>
        <el-tag v-else-if="scope.row.status === 2" type="success">全部确认</el-tag>
        <el-tag v-else-if="scope.row.status === 3" type="danger">拣货中</el-tag>
        <el-tag v-else-if="scope.row.status === 4" type="danger">已上货</el-tag>
      </template>
    </el-table-column>
    <el-table-column fixed="right" label="操作" min-width="120">
      <template #default="scope">
        <el-button link type="primary" size="small" @click="handleClick(scope.row)">
          修改
        </el-button>
        <el-button link type="danger" size="small" @click="remove(scope.row)">删除</el-button>
      </template>
    </el-table-column>
  </el-table>

  <!--分页-->
  <el-pagination
    v-model:current-page="page"
    v-model:page-size="pageSize"
    :page-sizes="[10, 20, 30, 40]"
    layout="total, sizes, prev, pager, next, jumper"
    :total="total"
    @size-change="handleSizeChange"
    @current-change="handleCurrentChange"
  />

  <!--对话框-->
  <el-dialog
    v-model="dialogVisible"
    :title="isEdit ? '修改入库单' : '添加入库单'"
    width="600"
    :before-close="handleClose"
  >
    <el-form :model="disForm" label-width="120px">
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="货主Id">
            <el-input v-model="disForm.consignorId" placeholder="请输入货主Id" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="到达总数">
            <el-input v-model="disForm.totalCount" placeholder="到达总数" />
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="批次号">
            <el-input v-model="disForm.batchNumber" placeholder="请输入批次号" />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="预计到达时间">
            <el-date-picker
              v-model="disForm.predictedArrivalTime"
              type="datetime"
              placeholder="请选择预计到达时间"
              style="width: 100%"
              value-format="YYYY-MM-DDTHH:mm:ss"
              format="YYYY-MM-DD HH:mm:ss"
            />
          </el-form-item>
        </el-col>
          <el-col :span="24">
        
        </el-col>
      </el-row>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="save">
          {{ isEdit ? '修改' : '保存' }}
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<style scoped>
.el-table {
  margin-top: 20px;
}

.el-pagination {
  margin-top: 20px;
  justify-content: flex-end;
}
</style>
